<?php

namespace app\common\model\xiluedu;

use app\common\library\Auth;
use think\Db;
use think\Log;
use think\Model;
use traits\model\SoftDelete;
use function fast\array_get;

class Course extends Model
{

    use SoftDelete;

    

    // 表名
    protected $name = 'xiluedu_course';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'type_text',
        'is_charge_text',
        'is_hot_text',
        'is_new_text',
        'status_text'
    ];

    
    public function getTypeList()
    {
        return ['1' => __('Type 1'), '2' => __('Type 2'), '3' => __('Type 3')];
    }

    public function getIsChargeList()
    {
        return ['0' => __('Is_charge 0'), '1' => __('Is_charge 1')];
    }

    public function getIsHotList()
    {
        return ['0' => __('Is_hot 0'), '1' => __('Is_hot 1')];
    }

    public function getIsNewList()
    {
        return ['0' => __('Is_new 0'), '1' => __('Is_new 1')];
    }

    public function getStatusList()
    {
        return ['0' => __('Status 0'), '1' => __('Status 1')];
    }
    #缩略图
    public function getThumbImageAttr($value,$data){
        return $value ? cdnurl($value,true) :'';
    }
    #轮播图
//    public function getImagesAttr($value,$data){
//        if($value && is_string($value)){
//            $images = explode(',',$value);
//            foreach ($images as &$image){
//                $image = cdnurl($value,true);
//            }
//        }else{
//            $images = [];
//        }
//        return $images;
//    }

    public function getTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['type']) ? $data['type'] : '');
        $list = $this->getTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function getIsChargeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['is_charge']) ? $data['is_charge'] : '');
        $list = $this->getIsChargeList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getIsHotTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['is_hot']) ? $data['is_hot'] : '');
        $list = $this->getIsHotList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getIsNewTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['is_new']) ? $data['is_new'] : '');
        $list = $this->getIsNewList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function teacher(){
        return $this->belongsTo('Teacher','teacher_id','id',[],'LEFT')->setEagerlyType(1);
    }

    public function courseFile(){
        return $this->hasMany(CourseFile::class,'course_id','id');
    }

    /**
     * 课程列表
     * @param $pagesize
     */
    public static function videoAudioSortLists($pagesize){
        $video_sort = static::field('id,type,name,category_id,tag_ids,teacher_id,thumb_image,description,is_charge,try_times,(basic_num+real_num) total_num,collection_count,avg_score')
            ->where("type",'1')
            ->where("status",'1')
            ->order("view_count",'desc')
            ->limit($pagesize)
            ->select();
        $audio_sort = static::field('id,type,name,category_id,tag_ids,teacher_id,image,description,is_charge,try_times,(basic_num+real_num) total_num,collection_count,avg_score')
            ->where("type",'2')
            ->where("status",'1')
            ->order("view_count",'desc')
            ->limit($pagesize)
            ->select();
        return ['video_sort'=>$video_sort,'audio_sort'=>$audio_sort];
    }

    /**
     * 课程列表
     * @param $params
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public static function searchLists($params){
        $query = static::with(['teacher'])
            ->field('id,type,name,category_id,tag_ids,teacher_id,thumb_image,description,is_charge,(basic_num+real_num) total_num,collection_count,salesprice,play_count');

        if($category_id = array_get($params,'category_id')){
            //$query->where('category_id',$category_id);
            $query->where("FIND_IN_SET(".(int)$category_id.",category_ids)");
        }
        $pagesize = array_get($params,'pagesize',10);
        #关键词搜索
        if($q = array_get($params,'q')){
            $query->where('name','like',"%$q%");
            try {
                if (Db::name('xiluedu_search_keyword')->where('keyword', $q)->count() > 0) {
                    Db::name('xiluedu_search_keyword')->where('keyword', $q)->update([
                        'search_count' => Db::raw('search_count+1')
                    ]);
                } else {
                    Db::name('xiluedu_search_keyword')->insert(['keyword' => $q, 'search_count' => 1]);
                }
            }catch (\Exception $e) {
                Log::error($e->getMessage()."\n".$e->getTraceAsString());
            }
        }
        //课程类型搜索
        if($type = array_get($params,'type')){
            $query->where('type',$type);
        }
        #标签搜索
        if($tag_id = array_get($params,'tag_id')){
            switch ($tag_id){
                case 1:
                    #免费
                    $query->where('is_charge','0');
                    break;
                case 2:
                    #VIP
                    $query->where('is_charge','1');
                    break;
                case 3:
                    #热门
                    $query->where('is_hot','1');
                    break;
                case 4:
                    #热门
                    $query->where('type','1');
                    break;
                case 5:
                    #音频
                    $query->where('type','2');
                    break;
            }
        }

        #排序
        $sort_name = array_get($params,'sort_name','weigh');
        $sort_order = array_get($params,'sort_order','desc');

        $paginator = $query->where('status','1')
            ->order($sort_name,$sort_order)
            ->paginate($pagesize);
        return $paginator;
    }

    /**
     * 猜你喜欢
     * @param null $course_id
     */
    public static function guessLike($course_id=NULL,$pagesize=6){
        $query = static::with(['teacher'])
            ->field('id,type,name,category_id,tag_ids,teacher_id,thumb_image,description,is_charge,(basic_num+real_num) total_num,collection_count,salesprice,play_count')
            ->where('status','1');
        if($course_id){
            $course = static::get($course_id);
//            $query->where('category_id',$course->category_id)
//                ->where('id','<>',$course_id);
            $lists = $query->order("total_num",'desc')
                ->paginate($pagesize);
        }else{
            $auth = Auth::instance();
            if($auth->isLogin()){
                #个人定制数据条件

            }
            $query->where('is_hot','1');
            $lists = $query->orderRaw("RAND()")
                ->select();
        }

        return $lists;
    }

}
